package com.voice.client.channel;

import com.alibaba.fastjson.JSONObject;
import com.voice.client.channel.handle.impl.DeviceChannelStreamListener;
import com.voice.client.message.entity.Message;
import com.voice.client.message.impl.MessageClientImpl;
import com.voice.core.DefaultClient;
import com.voice.core.ResponseCodeEnum;
import com.voice.core.connection.Connection;
import com.voice.core.connection.callback.AbstractStreamListener;
import com.voice.core.connection.entity.Stream;
import com.voice.core.connection.entity.StreamData;
import com.voice.core.entity.HttpHeader;
import com.voice.core.utils.MessageUtil;
import com.voice.core.utils.ResponseUtil;
import com.wangjiacai.utils.output.ResultVO;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class DefaultStreamListener extends AbstractStreamListener {

    private DefaultClient defaultClient;
    private DeviceChannelStreamListener deviceChannelStreamListener;
    private MessageClientImpl messageClient;

    public DefaultStreamListener(MessageClientImpl messageClient,DeviceChannelStreamListener deviceChannelStreamListener) {
        this.deviceChannelStreamListener = deviceChannelStreamListener;
        this.defaultClient = new DefaultClient();
        this.messageClient=messageClient;
    }

    @Override
    public void onHeadersRead(Connection connection, Stream stream, HttpHeader requestHeader, boolean endOfStream) {
        Message message=new Message(requestHeader.toString().getBytes(), MessageUtil.messageId(),2);
        try {
            Message response = messageClient.publish("/device/authentication",message).get(30, TimeUnit.SECONDS);
            if(response==null ) this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.error(ResponseCodeEnum.Unauthorized), () -> connection.close());
            ResultVO<String> resultVO= JSONObject.parseObject(response.getPayload(),ResultVO.class);
            if (resultVO==null||resultVO.getData() == null) {
                this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.error(ResponseCodeEnum.Unauthorized), () -> connection.close());
            } else {
                requestHeader.put("userId", resultVO.getData());
                deviceChannelStreamListener.handle(requestHeader, connection);
                this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.success());
            }
        } catch (Exception e) {
            this.defaultClient.sendResponse(connection, stream.getStreamId(), ResponseUtil.error(ResponseCodeEnum.Unauthorized), () -> connection.close());
        }
    }

    @Override
    public void onDataRead(Connection connection, Stream stream, StreamData streamData) {
    }

}
